package com.thread.plbc;

/**
 * @author げっしょく
 * @date 2021/8/5
 */
public class ThreadDemo6 {
    //死锁怎么写
    public static void main(String[] args) {
        Object o1 = new Object();
        Object o2 = new Object();
        Thread t1 = new ThreadD6exer(o1 , o2);
        Thread t2 = new ThreadD6exer2(o1 , o2);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        t2.start();
    }
}

class  ThreadD6exer extends Thread{
    Object o1 = new Object();
    Object o2 = new Object();
    public ThreadD6exer(Object o1 , Object o2){
        this.o1 = o1;
        this.o2 = o2;
    }
    @Override
    public void run() {
        synchronized (o1){
            //不加睡眠的话，可能是当前线程抢到cpu时间片，
            // 就能在该时间中完成锁完两个并释放
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (o2){

            }
        }
    }
}

class  ThreadD6exer2 extends Thread{
    Object o1 = new Object();
    Object o2 = new Object();
    public ThreadD6exer2(Object o1 , Object o2){
        this.o1 = o1;
        this.o2 = o2;
    }
    @Override
    public void run() {
        synchronized (o2){
            //不加睡眠的话，可能是当前线程抢到cpu时间片，
            // 就能在该时间中完成锁完两个并释放
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (o1){

            }
        }
    }
}

